package com.gzdh.dishrecognition.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.StringUtils;
import com.dhkj.web.utils.MyObserverRes;
import com.dhkj.web.utils.RequestUtils;
import com.gzdh.dishrecognition.R;
import com.gzdh.dishrecognition.config.SysConstConfig;
import com.gzdh.dishrecognition.emu.OfflineGetCardSnTypeEmus;
import com.gzdh.dishrecognition.model.LcReportDto;
import com.gzdh.dishrecognition.ui.adapter.report.ScanTakeAdapter;
import com.gzdh.dishrecognition.ui.base.BaseMVCActivity;
import com.gzdh.dishrecognition.ui.dialog.MsgDialog;
import com.gzdh.dishrecognition.ui.pre.ScanTakePre;
import com.gzdh.dishrecognition.ui.view.OptionItemView;
import com.gzdh.dishrecognition.util.ByteUtil;
import com.gzdh.dishrecognition.util.ScanKeyManager;
import com.gzdh.dishrecognition.util.SystemUtils;
import com.jiebao.nfc.uartnfc.CardReaderDevice;
import com.serialport.JBScanner;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class ScanTakeFoodActivity extends BaseMVCActivity {

    private Context mContext;

    private ScanTakePre scanTakePre;

    private JBScanner scanner;

    private ScanKeyManager scanKeyManager;

    private Timer timer;

    private OptionItemView cardId;

    private OptionItemView cardName;

    private OptionItemView cardBalance;

    private OptionItemView cardSubsidy;

    private RelativeLayout msgRv;

    private LinearLayout dataLinear;

    private RecyclerView recyclerView;

    private LinearLayout dateMsgLinear;

    private ScanTakeAdapter scanTakeAdapter;

    private TextView totalNumberTv;

    private TextView totalPriceTv;

    private TextView clearTv;

    private TextView sureTakeTv;


    public static void start(Context context) {
        context.startActivity(new Intent(context, ScanTakeFoodActivity.class));
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_scan_take;
    }

    @Override
    protected void initView() {
        mContext = this;
        findViewById(R.id.backBut).setOnClickListener(view -> {
            if(scanTakePre != null) {
                scanTakePre.clear();
                scanTakePre.hide();
            }
            finish();
        });
        TextView titleTv = findViewById(R.id.titleTv);
        titleTv.setText("人员信息");

        int fontSize = SysConstConfig.getInstance().getScanTakeFontSize();
        cardId = findViewById(R.id.cardId);
        cardId.setLeftTextSize(fontSize);
        cardId.setRightTextSize(fontSize);

        cardName = findViewById(R.id.cardName);
        cardName.setLeftTextSize(fontSize);
        cardName.setRightTextSize(fontSize);

        cardBalance = findViewById(R.id.card_balance);
        cardBalance.setLeftTextSize(fontSize);
        cardBalance.setRightTextSize(fontSize);

        cardSubsidy = findViewById(R.id.card_subsidy);
        cardSubsidy.setLeftTextSize(fontSize);
        cardSubsidy.setRightTextSize(fontSize);

        msgRv = findViewById(R.id.msgRv);
        dataLinear = findViewById(R.id.dataLinear);
        recyclerView = findViewById(R.id.recyclerView);
        dateMsgLinear = findViewById(R.id.dateMsgLinear);

        totalNumberTv = findViewById(R.id.total_number);
        totalNumberTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
        totalPriceTv = findViewById(R.id.total_price);
        totalPriceTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);

        clearTv = findViewById(R.id.clearTv);
        sureTakeTv = findViewById(R.id.sureTakeTv);
    }

    @Override
    protected void initData() {
        clearTv.setOnClickListener(view -> {
            msgRv.setVisibility(View.VISIBLE);
            dataLinear.setVisibility(View.GONE);
            scanTakeAdapter.setDinner("");
            scanTakeAdapter.setLcReportDtoList(new ArrayList<>());
            cardId.setRightText("");
            cardName.setRightText("");
            cardBalance.setRightText("");
            cardSubsidy.setRightText("");
            totalNumberTv.setText("");
            totalPriceTv.setText("");
            if(scanTakePre != null) {
                scanTakePre.clear();
            }
        });

        sureTakeTv.setOnClickListener(view -> {
            List<Long> pkIdList = scanTakeAdapter.getPkIdList();
            if(pkIdList.size() == 0) {
                MsgDialog msgDialog = new MsgDialog(mContext);
                msgDialog.show();
                TextView msg = msgDialog.getMsgTv();
                msg.setText("没有要确认领餐的记录");
                msg.setTextSize(30);
                return;
            }
            RequestUtils.receiveFood(mContext, pkIdList, new MyObserverRes<>(mContext) {
                @Override
                public void onSuccess(String result) {
                    Toast.makeText(mContext, "操作成功", Toast.LENGTH_SHORT).show();
                    recyclerView.setVisibility(View.GONE);
                    dateMsgLinear.setVisibility(View.VISIBLE);
                    scanTakeAdapter.setDinner("");
                    scanTakeAdapter.setLcReportDtoList(new ArrayList<>());
                    totalNumberTv.setText("");
                    totalPriceTv.setText("");
                    DisplayMetrics metrics = new DisplayMetrics();
                    getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
                    if(scanTakePre != null) {
                        scanTakePre.sureTake(metrics);
                    }
                }

                @Override
                public void onFailure(Throwable e, String errorMsg) {
                    MsgDialog msgDialog = new MsgDialog(mContext);
                    msgDialog.show();
                    TextView msg = msgDialog.getMsgTv();
                    msg.setText(errorMsg);
                    msg.setTextSize(30);
                }
            });
        });
    }

    @Override
    protected void dissmissPresnetation() {

    }

    @Override
    public void onResume() {
        super.onResume();
        switch (SysConstConfig.getInstance().getPeripheralDeviceModel()) {
            case defaultType:
                CardReaderDevice.getInstance().initCardReader();
                scanner = new JBScanner(code -> {
                    if (code.length() < 10) {
                        onCard(code);
                    } else {
                        getDataList(code);
                    }
                });
                scanner.startScan();
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        String cardNo = CardReaderDevice.getInstance().readCardNo();
                        if (!StringUtils.isEmpty(cardNo)) {
                            onCard(cardNo);
                        }
                    }
                }, 0, 3000);
                break;
            case cloudQrAndReadCard:
                System.out.println("云设备");
                scanKeyManager = new ScanKeyManager((String value) -> {
                    Log.i("MainActivity", "ScanValue->" + value);
                    if (value.length() < 10) {
                        onCard(value);
                    } else {
                        getDataList(value);
                    }
                });
                break;
        }
        scanTakeAdapter = new ScanTakeAdapter(mContext);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
    }

    public void onCard(String auth) {
        if(SysConstConfig.getInstance().getOfflineGetCardSnType() == OfflineGetCardSnTypeEmus.reverse) {
            byte[] cardSnTemp = ByteUtil.hexStringToByte(auth.toUpperCase());
            byte[] cardSn = new byte[4];
            for (int i = 0; i < cardSnTemp.length; i++) {
                cardSn[i] = cardSnTemp[3 - i];
            }
            getDataList(ByteUtil.bytesToHexString(cardSn).toUpperCase());
        } else {
            getDataList(auth);
        }
    }

    private void getDataList(String auth) {
        RequestUtils.getTakeFoodList(mContext, SystemUtils.getSerialNumber(), auth, new MyObserverRes<>(mContext, false) {
            @Override
            public void onSuccess(JSONObject result) {
                System.out.println(result.toJSONString());
                msgRv.setVisibility(View.GONE);
                dataLinear.setVisibility(View.VISIBLE);

                JSONObject fkJson = result.getJSONObject("fk");
                cardId.setRightText(fkJson.getString("id"));
                cardName.setRightText(fkJson.getString("name"));
                cardBalance.setRightText(fkJson.getString("kye"));
                cardSubsidy.setRightText(fkJson.getString("btye"));

                List<LcReportDto> list = result.getJSONArray("dataList").toJavaList(LcReportDto.class);
                if (list.isEmpty()) {
                    recyclerView.setVisibility(View.GONE);
                    dateMsgLinear.setVisibility(View.VISIBLE);
                } else {
                    recyclerView.setVisibility(View.VISIBLE);
                    dateMsgLinear.setVisibility(View.GONE);
                }
                recyclerView.setAdapter(scanTakeAdapter);
                scanTakeAdapter.setDinner(result.getString("dinnerName"));
                scanTakeAdapter.setLcReportDtoList(list);

                BigDecimal totalNumber = new BigDecimal(0);
                BigDecimal totalPrice = new BigDecimal(0);
                for (LcReportDto lcReportDto : list) {
                    totalNumber = totalNumber.add(new BigDecimal(lcReportDto.getSl()));
                    totalPrice = totalPrice.add(new BigDecimal(lcReportDto.getJe()));
                }
                totalNumberTv.setText(totalNumber.stripTrailingZeros().toPlainString());
                totalPriceTv.setText(totalPrice.setScale(2, RoundingMode.DOWN).toPlainString());
                if(scanTakePre != null) {
                    scanTakePre.showData(list, result.getString("dinnerName"),
                            totalNumber.stripTrailingZeros().toPlainString(),
                            totalPrice.setScale(2, RoundingMode.DOWN).toPlainString());
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                System.out.println("errorMsg:" + errorMsg);
                msgRv.setVisibility(View.VISIBLE);
                dataLinear.setVisibility(View.GONE);
                cardId.setRightText("");
                cardName.setRightText("");
                cardBalance.setRightText("");
                cardSubsidy.setRightText("");
                totalNumberTv.setText("");
                totalPriceTv.setText("");
                MsgDialog msgDialog = new MsgDialog(mContext);
                msgDialog.show();
                TextView msg = msgDialog.getMsgTv();
                msg.setText(errorMsg);
                msg.setTextSize(30);
            }
        });
    }

    @Override
    public void initPresentation() {
        super.initPresentation();
        if (mDisplay != null) {
            scanTakePre = new ScanTakePre(ScanTakeFoodActivity.this, mDisplay);
            registerPresentation(scanTakePre);
            showPresentation(scanTakePre);
            scanTakePre.show();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
            scanKeyManager.analysisKeyEvent(event);
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (scanner != null) {
            scanner.stopScan();
            scanner = null;
        }
        if(timer != null) {
            timer.cancel();
        }
    }
}
